import { PayloadAction, createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { AsyncState, ListState } from '..'
import { Category, apiDeleteCategory, apiGetCategoryList, apiPostCategory, apiPutCategory } from '../../api/category'

type CategoryState = AsyncState & Omit<ListState<Category>, 'pager'> & {
    current: number
}
const initialState: CategoryState = {
    status: 'idle',
    error: null,
    list: [],
    current: 0
}

export const fetchCategories = createAsyncThunk('category/fetchCategories', apiGetCategoryList)
export const createCategory = createAsyncThunk('category/createCategory', apiPostCategory)
export const updateCategory = createAsyncThunk('category/updateCategory', apiPutCategory)
export const deleteCategory = createAsyncThunk('category/deleteCategory', apiDeleteCategory)
export const categorySlice = createSlice({
    name: 'category',
    initialState: initialState,
    reducers: {
        categoryIdChange(state, action: PayloadAction<number|null>) {
            console.log(action.payload)
            
            if(action.payload){
                state.current = action.payload
            }else{
                state.current = 0
            }
        }
    },
    extraReducers(builder) {
        builder
            .addCase(fetchCategories.pending, (state) => {
                state.status = 'loading'
            })
            .addCase(fetchCategories.fulfilled, (state, action) => {
                state.status = 'succeeded'
                state.list = action.payload.list
                state.current = state.list[0]?.id || 0
            })
            .addCase(fetchCategories.rejected, (state) => {
                state.status = 'failed'
                state.error = '获取分类列表失败'
            })
            .addCase(createCategory.fulfilled, (state) => {
                state.status = 'idle'
            })
            .addCase(updateCategory.fulfilled, (state) => {
                state.status = 'idle'
            })
            .addCase(deleteCategory.fulfilled, (state) => {
                state.status = 'idle'
            })
    }
})
export const { categoryIdChange } = categorySlice.actions
export default categorySlice.reducer